package com.hashnode.proj0001firstspringsecurity.config;

import com.hashnode.proj0001firstspringsecurity.authentication.filters.InitialAuthenticationFilter;
import com.hashnode.proj0001firstspringsecurity.authentication.filters.JwtAuthenticationFilter;
import com.hashnode.proj0001firstspringsecurity.authentication.providers.OtpAuthenticationProvider;
import com.hashnode.proj0001firstspringsecurity.authentication.providers.UsernamePasswordAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;


@Configuration
//扩展了WebSecurityConfigurerAdapter，以覆盖SecurityConfigurer的configure()方法。
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //自动注入过滤器和我们在配置中设置的认证提供者。
    @Autowired
    private InitialAuthenticationFilter initialAuthenticationFilter;

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Autowired
    private OtpAuthenticationProvider otpAuthenticationProvider;

    @Autowired
    private UsernamePasswordAuthenticationProvider usernamePasswordAuthenticationProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        //向认证管理器配置两个认证提供者
        auth.authenticationProvider(otpAuthenticationProvider)
            .authenticationProvider(usernamePasswordAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //禁用CSRF保护
        http.csrf().disable();

        //将两个自定义过滤器添加到过滤器链中
        http.addFilterAt(
                initialAuthenticationFilter,
                BasicAuthenticationFilter.class)
            .addFilterAfter(
                jwtAuthenticationFilter,
                BasicAuthenticationFilter.class
            );

        //确保所有请求都经过认证
        http.authorizeRequests()
                .anyRequest().authenticated();
    }

    //将AuthenticationManager添加到Spring上下文中，这样我们就可以从过滤器类中自动注入它。
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }



}
